package com.dlc.shop.live.platform.task;

import cn.hutool.core.collection.CollUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.dlc.shop.bean.dto.wukong.ChanneDeleteDTO;
import com.dlc.shop.bean.enums.LiveRoomStatusType;
import com.dlc.shop.common.util.Json;
import com.dlc.shop.common.wukongim.constant.WuKongConstant;
import com.dlc.shop.live.common.dao.LiveRoomMapper;
import com.dlc.shop.live.common.service.LiveRoomService;
import com.dlc.shop.live.common.vo.LiveMsgItem;
import com.dlc.shop.wukongim.service.WuKongImService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 直播的定时任务
 * @author LHD
 */
@Component
@AllArgsConstructor
public class LiveTask {
    private static final Logger logger = LoggerFactory.getLogger(LiveTask.class);

    private final LiveRoomService liveRoomService;
    private final LiveRoomMapper liveRoomMapper;
    private final WuKongImService wuKongImService;

    /**
     * 定时改变直播间状态 半小时一次
     */
    @XxlJob("changeLiveRoomStatus")
    public void changeLiveRoomStatus() {
        // 查询要关播的直播间列表
        List<Long> endLiveRoomIds = liveRoomMapper.listLiveRoomByStatus(LiveRoomStatusType.FINISHED.value());
        if (CollUtil.isNotEmpty(endLiveRoomIds)) {
            // 更新直播间状态
            logger.info("直播间关播:{}", endLiveRoomIds);
            liveRoomService.updateLiveRoomStatus(LiveRoomStatusType.FINISHED.value(), endLiveRoomIds);
            // 删除频道
            for (Long endLiveRoomId : endLiveRoomIds) {
                wuKongImService.deleteChannel(new ChanneDeleteDTO(WuKongConstant.LIVE_CHANNEL_PREFIX + endLiveRoomId, 2));
                // 发送直播结束消息
                LiveMsgItem statusMsg = new LiveMsgItem(WuKongConstant.LIVE_STATUS, LiveRoomStatusType.FINISHED.value());
                wuKongImService.sendLiveRoomMessage(WuKongConstant.LIVE_CHANNEL_PREFIX + endLiveRoomId, Json.toJsonString(statusMsg), null);
            }
        }
    }
}
